package com.lap.generator.domain.template.strategy;

import com.lap.generator.application.assembler.ModelTransformer;
import com.lap.generator.commons.exception.GeneratorException;
import com.lap.generator.commons.tools.FileUtil;
import com.lap.generator.commons.tools.PackageUtil;
import com.lap.generator.domain.CoreFile;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.template.CodeGenContext;
import com.lap.generator.domain.template.CodeTemplate;
import com.lap.generator.domain.valueobject.CodeType;
import com.lap.generator.infrastructure.persistence.TemplateEngine;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class QueryRepositoryGen implements CodeTemplate<CoreFile> {
  @Override
  public CodeType getType() {
    return CodeType.APP_SERVICE;
  }

  @Override
  public List<CoreFile> generate(CodeGenContext context) {
    TemplateModel model = ModelTransformer.transform(context.tableMeta(), context.envConfig());
    try {
      TemplateEngine engine = new TemplateEngine();
      String repositoryContent = engine.processTemplate("application/QueryRepository.java.ftl", model);
      String repositoryPackName = PackageUtil.pack2Path(model.getBasePackage(), "application",
          model.getModule(), "repository");
      String repositoryFileName = FileUtil.resolverFile("java", model.getClassName(), "QueryRepository");
      CoreFile repositoryFile =
          CoreFile.builder().path(repositoryPackName).fileName(repositoryFileName).content(repositoryContent).build();

      return List.of(repositoryFile);
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("QueryRepository engine error:", e);
    }
  }
}
